package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.BdmCart;
import com.ruoyi.system.domain.BdmGood;
import com.ruoyi.system.domain.BdmOrder;
import com.ruoyi.system.domain.BdmOrderItem;
import com.ruoyi.system.domain.dto.BdmCartDto;
import com.ruoyi.system.enums.BdmMemberRuleEnum;
import com.ruoyi.system.mapper.BdmCartMapper;
import com.ruoyi.system.mapper.BdmGoodMapper;
import com.ruoyi.system.mapper.BdmMemberRuleMapper;
import com.ruoyi.system.service.IBdmCartService;
import com.ruoyi.system.domain.vo.BdmCartVo;
import com.ruoyi.system.domain.vo.BdmMemberRuleVo;
import com.ruoyi.system.service.IBdmOrderItemService;
import com.ruoyi.system.service.IBdmOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 购物车Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-12
 */
@Service
public class BdmCartServiceImpl extends ServiceImpl<BdmCartMapper,BdmCart> implements IBdmCartService {

    @Autowired
    private BdmCartMapper bdmCartMapper;

    @Autowired
    private BdmGoodMapper bdmGoodMapper;

    @Autowired
    private BdmMemberRuleMapper bdmMemberRuleMapper;

    @Autowired
    private IBdmOrderService iBdmOrderService;

    @Autowired
    private IBdmOrderItemService bdmOrderItemService;

    /**
     * 查询购物车
     *
     * @param id 购物车主键
     * @return 购物车
     */
    @Override
    public BdmCart selectBdmCartById(Long id) {
        return bdmCartMapper.selectBdmCartById(id);
    }

    /**
     * 查询购物车列表
     *
     * @param bdmCart 购物车
     * @return 购物车
     */
    @Override
    public List<BdmCart> selectBdmCartList(BdmCart bdmCart) {
        return bdmCartMapper.selectBdmCartList(bdmCart);
    }

    /**
     * 新增购物车
     *
     * @param bdmCart 购物车
     * @return 结果
     */
    @Override
    public int insertBdmCart(BdmCart bdmCart) {
        bdmCart.setCreateTime(DateUtils.getNowDate());
        return bdmCartMapper.insertBdmCart(bdmCart);
    }

    /**
     * 修改购物车
     *
     * @param bdmCart 购物车
     * @return 结果
     */
    @Override
    public int updateBdmCart(BdmCart bdmCart) {
        bdmCart.setUpdateTime(DateUtils.getNowDate());
        return bdmCartMapper.updateBdmCart(bdmCart);
    }

    /**
     * 批量删除购物车
     *
     * @param ids 需要删除的购物车主键
     * @return 结果
     */
    @Override
    public int deleteBdmCartByIds(Long[] ids) {
        return bdmCartMapper.deleteBdmCartByIds(ids);
    }

    /**
     * 删除购物车信息
     *
     * @param id 购物车主键
     * @return 结果
     */
    @Override
    public int deleteBdmCartById(Long id) {
        return bdmCartMapper.deleteBdmCartById(id);
    }

    /**
     * 查询用户购物车
     *
     * @param userId
     * @return
     */
    @Override
    public List<BdmCartVo> getUserCart(Long userId) {
        // 获取当前用户等级
        BdmMemberRuleVo memberRuleVo = bdmMemberRuleMapper.selectMemberRuleByUserId(userId);
        return bdmCartMapper.getUserCart(userId).stream().peek(item -> {
            BdmGood bdmGood = bdmGoodMapper.selectbdmGoodById(item.getProductId());
            item.setRepertoryFlag(item.getCartNum() <= Integer.parseInt(bdmGood.getGoodInventory()));
            if (bdmGood.getIsInitiate().equals("2")) {
                item.setProductStatusFlag(false);
            }
            item.setGoodName(bdmGood.getGoodName());
            item.setGoodImg(bdmGood.getGoodImg());
            item.setGoodSpecs(bdmGood.getGoodSpecs());
            chenUserPrice(memberRuleVo, item, bdmGood);
            item.setOriginalPrice(bdmGood.getRetailPrice().multiply(new BigDecimal(item.getCartNum())));
        }).collect(Collectors.toList());
    }

    /**
     * 加入购物车
     *
     * @param dto
     * @return
     */
    @Override
    public boolean saveUserCart(BdmCartDto dto) {
        // 限购数量
        int count = 0;
        ArrayList<Long> orderStatus = new ArrayList<>();
        orderStatus.add(5L);
        orderStatus.add(6L);
        List<BdmOrder> orderList = iBdmOrderService.lambdaQuery().eq(BdmOrder::getUserId, dto.getUserId()).notIn(BdmOrder::getOrderStatus, orderStatus).list();
        if (!CollectionUtils.isEmpty(orderList)) {
            List<String> orderIds = orderList.stream().map(BdmOrder::getId).collect(Collectors.toList());
            int productCount = bdmOrderItemService.lambdaQuery().in(BdmOrderItem::getOrderId, orderIds)
                    .list()
                    .stream()
                    .filter(item -> dto.getProductId().equals(Long.parseLong(item.getSupplierGoodId()))).mapToInt(item -> Integer.parseInt(item.getGoodCount())).sum();
            count += productCount;
        }

        BdmCart bdmCart = new BdmCart();
        bdmCart.setProductId(dto.getProductId());
        bdmCart.setUserId(dto.getUserId());
        List<BdmCart> bdmCarts = bdmCartMapper.selectBdmCartList(bdmCart);
        if (CollectionUtils.isEmpty(bdmCarts)) {
            BeanUtils.copyProperties(dto, bdmCart);
            bdmCart.setCreateTime(new Date());
            bdmCart.setCartNum(1);
            extracted(dto, bdmCart.getCartNum());
            bdmCartMapper.insertBdmCart(bdmCart);
        } else {
            BdmGood bdmGood = bdmGoodMapper.selectbdmGoodById(dto.getProductId());
            if (bdmGood.getProductLevel() != null) {
                if (bdmGood.getProductLevel() >= 3) {
                    throw new RuntimeException("vip礼包或大礼包只能购买一份");
                }else if (bdmGood.getProductLevel()>=1){
                    // 限购数量
                    Long inventoryVersion = bdmGood.getInventoryVersion();
                    if ((bdmCarts.get(0).getCartNum()+count) >= inventoryVersion) {
                        throw new RuntimeException("超过vip礼包限购次数");
                    }
                }

            }
            BdmCart update = bdmCarts.get(0);
            int cartNum = update.getCartNum() + 1;
            extracted(dto, cartNum);

            update.setCartNum(cartNum);
            update.setUpdateTime(DateUtils.getNowDate());
            bdmCartMapper.updateBdmCart(update);
        }
        return true;
    }


    /**
     * 增加购物车商品数量
     *
     * @param dto
     * @return
     */
    @Override
    public boolean plusUserCartNumber(BdmCartDto dto) {
        saveUserCart(dto);
        return true;
    }

    /**
     * 减少购物车商品数量
     *
     * @param dto
     * @return
     */
    @Override
    public boolean reduceUserCartNumber(BdmCartDto dto) {
        BdmCart bdmCart = bdmCartMapper.selectBdmCartById(dto.getId());
        Integer cartNum = bdmCart.getCartNum();
        if (cartNum - 1 == 0) {
            bdmCartMapper.deleteBdmCartById(bdmCart.getId());
        } else {
            bdmCart.setCartNum(cartNum - 1);
            bdmCartMapper.updateBdmCart(bdmCart);
        }
        return true;
    }

    /**
     * 清空购物车商品
     *
     * @param userId
     * @return
     */
    @Override
    public boolean emptyUserCart(Long userId) {
        bdmCartMapper.emptyUserCart(userId);
        return true;
    }

    private void extracted(BdmCartDto dto, int cartNum) {
        BdmGood bdmGood = bdmGoodMapper.selectbdmGoodById(dto.getProductId());
        if (bdmGood == null) {
            throw new RuntimeException("商品不存在");
        }
        if (bdmGood.getIsInitiate().equals("2")) {
            throw new RuntimeException("商品已下架");
        }
        if (Integer.parseInt(bdmGood.getGoodInventory()) < cartNum) {
            throw new RuntimeException("超过该商品库存");
        }
    }

    /**
     * 校验用户价格
     *
     * @param memberRuleVo
     * @param item
     * @param bdmGood
     */
    private void chenUserPrice(BdmMemberRuleVo memberRuleVo, BdmCartVo item, BdmGood bdmGood) {
        // 普通用户价格
            item.setRetailPrice(bdmGood.getRetailPrice());
        // vip价格
        if (ObjectUtils.isEmpty(bdmGood.getProductLevel())&&memberRuleVo != null && memberRuleVo.getMemberLevel().equals(BdmMemberRuleEnum.VIP.getLevel())) {
            item.setRetailPrice(bdmGood.getVipPrice());
        }

        // svip价格
        if (ObjectUtils.isEmpty(bdmGood.getProductLevel())&&memberRuleVo != null && memberRuleVo.getMemberLevel().equals(BdmMemberRuleEnum.SVIP.getLevel())) {
            item.setRetailPrice(bdmGood.getSvipPrice());
        }
        // 共享店主
        if (ObjectUtils.isEmpty(bdmGood.getProductLevel())&&memberRuleVo != null && memberRuleVo.getMemberAgencyLevel() != null && memberRuleVo.getMemberAgencyLevel().equals(BdmMemberRuleEnum.SHOPKEEPER.getLevel())) {
            item.setRetailPrice(bdmGood.getSharePrice());
        }
        // 联创
        if (ObjectUtils.isEmpty(bdmGood.getProductLevel())&&memberRuleVo != null && memberRuleVo.getMemberAgencyLevel() != null && memberRuleVo.getMemberAgencyLevel().equals(BdmMemberRuleEnum.LAIN_CHANG.getLevel())) {
            item.setRetailPrice(bdmGood.getJoinPrice());
        }
        // 运营
        if (ObjectUtils.isEmpty(bdmGood.getProductLevel())&&memberRuleVo != null && memberRuleVo.getMemberAgencyLevel() != null && memberRuleVo.getMemberAgencyLevel().equals(BdmMemberRuleEnum.OPERATION.getLevel())) {
            item.setRetailPrice(bdmGood.getOperationsPrice());
        }
        // 总裁
        if (ObjectUtils.isEmpty(bdmGood.getProductLevel())&&memberRuleVo != null && memberRuleVo.getMemberAgencyLevel() != null && memberRuleVo.getMemberAgencyLevel().equals(BdmMemberRuleEnum.BOSS.getLevel())) {
            item.setRetailPrice(bdmGood.getPresidentPrice());
        }
    }

}
